package com.yj.forum.controller;

import com.yj.forum.common.AppConfig;
import com.yj.forum.common.AppResult;
import com.yj.forum.common.ResultCode;
import com.yj.forum.model.Message;
import com.yj.forum.model.User;
import com.yj.forum.services.IMessageService;
import com.yj.forum.services.IUserService;
import com.yj.forum.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Api(tags = "站内信接⼝")
@RestController
@RequestMapping("/message")
public class MessageController {
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;
    /**
     * 发送站内信
     * @param receiveUserId 接收⽤⼾Id
     * @param content 内容
     * @return AppResult
     */
    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                         @ApiParam("接收⽤⼾Id")@RequestParam("receiveUserId") Long receiveUserId,
                         @ApiParam("站内信内容")@RequestParam("content") String content) {
        //非空校验
        if(receiveUserId == null || receiveUserId <= 0  || StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //获取用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验是否禁言
        if(user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //不能给自己发送私信
        if(receiveUserId.equals(user.getId())) {
            log.warn("不能给⾃⼰发送站内信. postUserId = " + user.getId() + ", receiveUserId = " + receiveUserId);
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        // 查询接收⽤⼾
        User receiveUser = userService.selectById(receiveUserId);
        // ⽬标⽤⼾不存在
        if (receiveUser.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", receiveUserId = " + receiveUserId);
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //构造数据
        Message message = new Message();
        message.setContent(content);
        message.setReceiveUserId(receiveUserId);
        message.setPostUserId(user.getId());
        //调用service
        messageService.create(message);
        return AppResult.success();
    }

    /**
     * 获取未读消息个数
     * @return AppResult<Integer>
     */
    @ApiOperation("获取未读消息个数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //获取当前用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 调用service
        Integer result = messageService.selectUnreadCount(user.getId());

        return AppResult.success(result);
    }
    /**
     * 查询⽤⼾的所有站内信
     * @return 站内信集合
     */
    @ApiOperation("查询⽤⼾的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        // 获取当前登录⽤⼾
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 获取⽤⼾站内信
        List<Message> result = messageService.selectByReceiveUserId(user.getId());
        // 返回结果
        return AppResult.success(result);
    }
    /**
     * 更新状态为已读
     * @param id 站内信Id
     * @return AppResult<Message>
     */
    @ApiOperation("更新状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信Id")@RequestParam("id") Long id) {
        //非空校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //查询站内信
        Message message = messageService.selectById(id);
        if(message == null || message.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_MESSAGE_IS_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_MESSAGE_IS_NOT_EXISTS);
        }
        //获取用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 站内信不是⾃⼰的
        if(!user.getId().equals(message.getReceiveUserId())) {
            log.warn("查询了不属于⾃⼰的站内信：userId = " + user.getId() + ", receiveUserId = " + message.getReceiveUserId());
            return AppResult.failed(ResultCode.FAILED);
        }
        //调用service更新状态
        messageService.updateStateById(id,(byte)1);
        return AppResult.success();
    }
    /**
     * 回复站内信
     * @param repliedId 要回复的站内信Id
     * @param content 站内信的内容
     * @return AppResult
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信Id")@RequestParam("repliedId") Long repliedId,
                           @ApiParam("站内信的内容")@RequestParam("content") String content) {
        //非空校验
        if(repliedId == null || repliedId <= 0 || StringUtil.isEmpty(content)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //获取用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验是否禁言
        if(user.getState() != 0) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //获取要回复的站内信
        Message existsMessage = messageService.selectById(repliedId);
        if(existsMessage == null || existsMessage.getDeleteState() != 0) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_IS_NOT_EXISTS);
        }
        //不能给自己发
        if (user.getId().equals( existsMessage.getPostUserId())) {
            return AppResult.failed("不能回复⾃⼰的站内信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId()); // 发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); // 接收者
        message.setContent(content); // 内容
        // 调⽤Service
        messageService.reply(repliedId, message);
        // 返回结果
        return AppResult.success();
    }

}
